<style lang="less" scoped>
  .f-ww60 {
    width: 55% !important;
  }

  .f-ww80 {
    width: 80% !important;
  }

  .f-ww90 {
    width: 90% !important;
  }

  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }

  .el-col {
    border-radius: 4px;
  }

  .bg-purple-light {
    background: #ffffff;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .el-row {
    margin-bottom: 0;
    height: 40px;
  }

  .el-col-8 {
    height: 40px;
  }

  .active {
    display: none
  }

  .f-pl0 {
    padding-left: 0px !important;
  }
</style>
<template>
  <section>
    <el-form ref="searchForm" :model="searchForm" label-position="right" class="toolbar" style="height: 90px"
             label-width="120px">
      <el-row style="padding-top: 10px">
        <el-col :span="8">
          <div class="grid-content">
            <el-form-item label="客户名称" prop="memberUserId_EQ">
              <el-select class="f-ww90" v-model="searchForm.memberUserId_EQ"
                         remote
                         :remote-method="searchMemberUsers"
                         filterable
                         placeholder="请选择客户">
                <el-option v-for="mu in memberUsers" :label="mu.realName"
                           :key="mu.userId"
                           :value="mu.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content">
            <el-form-item label="结算方式" prop="paymentType_EQ">
              <el-select class="f-ww90" v-model="searchForm.paymentType_EQ"
                         placeholder="请选择结算方式">
                <el-option v-for="receivableType in $store.getters.PAY_WAY"
                           :label="receivableType.cnDictValname"
                           :key="receivableType.dictVal"
                           :value="receivableType.dictVal">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出账日期" prop="createDate">
            <el-date-picker class="f-ww90"
                            v-model="searchForm.createDate"
                            type="daterange"
                            placeholder="选择日期范围">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <div class="grid-content">
            <el-form-item label="对账单号" prop="invoiceNumber_LIKE">
              <el-input class="f-ww90" v-model="searchForm.invoiceNumber_LIKE"
                        placeholder="请输入对账单号"></el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content">
            <el-form-item label="账单状态" prop="invoiceStatus_EQ">
              <el-select class="f-ww90" v-model="searchForm.invoiceStatus_EQ"
                         placeholder="请选择账单状态">
                <el-option v-for="receivableType in $store.getters.INVOICE_TYPE"
                           :label="receivableType.cnDictValname"
                           :key="receivableType.dictVal"
                           :value="receivableType.dictVal">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content">
            <el-form-item label="账单周期" prop="invoicePeriod">
              <el-date-picker class="f-ww90"
                              v-model="searchForm.invoicePeriod"
                              type="daterange"
                              placeholder="选择日期范围">
              </el-date-picker>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div class="f-mt10">
      <el-button type="primary" @click="invoicesDialogClick">新增</el-button>
      <el-button type="primary" @click="invoiceExpress">导出</el-button>
      <el-button type="primary" class="f-fr" @click="resetSearchForm('searchForm')">重置</el-button>
      <el-button type="primary" class="f-fr" @click="searchFormBtn">查询</el-button>
    </div>

    <div class="f-mt10">
      <el-table :data="invoices" highlight-current-row border @sort-change="sortChange" @selection-change="selsChange"
                max-height="650">
        <el-table-column prop="invoiceNumber"  label="对账单号" width="170">
        </el-table-column>
        <el-table-column prop="createDate"  label="出账日期" width="120">
        </el-table-column>
        <el-table-column prop="paymentDate"  label="结算日期" width="120">
        </el-table-column>
        <el-table-column prop="paymentTypeName"  label="结算方式" width="120">
        </el-table-column>
        <el-table-column prop="memberUserName"  label="客户名称" width="130">
        </el-table-column>
        <el-table-column prop="orderNumber" label="账单周期" width="210">
          <template slot-scope="scope">
            {{scope.row.invoicePeriodStart}}-
            {{scope.row.invoicePeriodEnd}}
          </template>
        </el-table-column>
        <el-table-column prop="invoiceStatusName"  label="账单状态" width="120">
        </el-table-column>
        <el-table-column prop="latelyPaymentDate"  label="最近付款时间" width="150">
        </el-table-column>
        <el-table-column prop="invoiceTotalAmount"  label="账单总额/元" width="140">
        </el-table-column>
        <el-table-column prop="invoiceAdjustLaterTotalAmount"  label="调后总额/元" width="140">
        </el-table-column>
        <el-table-column prop="isAdjustName"  label="是否调整" width="120">
        </el-table-column>
        <el-table-column prop="paidAmount"  label="已付款金额/元" width="150">
        </el-table-column>
        <el-table-column prop="residueAmount"  label="剩余应付金额/元" width="180">
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" v-if="scope.row.invoiceStatus===102012001" @click="compileClick(scope.row.id)">
              编辑
            </el-button>
            <el-button type="danger" v-if="scope.row.invoiceStatus===102012001" @click="deleteInvoice(scope.row.id)">
              删除
            </el-button>
            <el-button type="primary" v-if="scope.row.invoiceStatus===102012001"
                       @click="confirmClick(scope.row.id,102012002)">确认
            </el-button>
            <el-button type="primary" v-if="scope.row.invoiceStatus===102012002||scope.row.invoiceStatus===102012003"
                       @click="selectClick(scope.row.id)">
              查看
            </el-button>
            <el-button type="primary"
                       v-if="scope.row.importTaxsheetDetail&&scope.row.invoiceStatus===102012002&&scope.row.isAdjust===111002002"
                       @click="adjustClick(scope.row.id)">
              账单调整
            </el-button>
            <el-button type="primary"
                       v-if="scope.row.importTaxsheetDetail&&scope.row.invoiceStatus===102012002&&scope.row.isAdjust===111002002&&scope.row.adjustAmount!==null"
                       @click="invoiceIsAdjustClick(scope.row.id,111002001)">确认调整
            </el-button>
            <el-button type="danger"
                       v-if="scope.row.importTaxsheetDetail&&scope.row.invoiceStatus===102012002&&scope.row.isAdjust===111002001"
                       @click="invoiceIsAdjustClick(scope.row.id,111002002)">取消调整
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
                     :current-page="currentPage"
                     :page-size="pageSize"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     layout="total,sizes,prev, pager, next, jumper"
                     :total="total" style="float: right">
      </el-pagination>
    </div>
    <div>
      <el-dialog :title="dialogTitle" :visible.sync="invoicesDialogForm" :close-on-click-modal="false">
        <el-form :model="invoiceForm" ref="invoiceForm" label-width="80px">
          <el-col :span="7">
            <el-form-item label=" 对账单号">
              <el-input :disabled="true" v-model="invoiceForm.invoiceNumber"
                        class="f-ww90"
                        placeholder="对账单号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="客户名称" prop="memberUserId"
                          :rules="{required: true, message: '请输入客户名称', trigger: 'blur'}">
              <el-select :disabled="clickType" class="f-ww90"
                         remote
                         :remote-method="searchMemberUsers"
                         filterable
                         v-model="invoiceForm.memberUserId"
                         placeholder="请选择客户名称">
                <el-option v-for="memberUser in memberUsers"
                           :label="memberUser.realName"
                           :key="memberUser.userId"
                           :value="memberUser.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="账单周期" prop="invoicePeriod"
                          :rules="{required: true,type:'array', message: '请输入账单周期', trigger: 'blur'}">
              <el-date-picker style="width: 90%;padding-left: 0 !important;" :disabled="clickType" class="f-pl0"
                              v-model="invoiceForm.invoicePeriod"
                              type="daterange"
                              placeholder="选择日期范围">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="账单总额" prop="invoiceTotalAmount" v-if="invoiceTotalAmountType === 1001">
              <el-input :disabled="true" v-model="invoiceForm.invoiceTotalAmount" class="f-ww90"
                        placeholder="账单总额"></el-input>
            </el-form-item>
            <el-form-item label="账单总额" prop="invoiceTotalAmount" v-if="invoiceTotalAmountType===1002">
              <el-input :disabled="true" v-model="invoiceForm.invoiceTotalAmount" class="f-ww90"
                        placeholder="账单总额"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="结算方式" prop="paymentType"
                          :rules="{required: true,type:'number', message: '请输入结算方式', trigger: 'blur'}">
              <el-select class="f-ww90" :disabled="clickType"
                         v-model.number="invoiceForm.paymentType"
                         placeholder="请选择结算方式">
                <el-option v-for="rt in $store.getters.PAY_WAY"
                           :label="rt.cnDictValname"
                           :key="rt.dictVal"
                           :value="rt.dictVal">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="结算日期" prop="paymentDate"
                          :rules="{type:'date',required: true, message: '请输入结算日期', trigger: 'blur'}">
              <el-date-picker style="width: 90%" :disabled="clickType"
                              v-model="invoiceForm.paymentDate"
                              type="date"
                              placeholder="选择日期范围">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-form>
        <div class="f-mb10">
          <el-button type="text" @click="importOrderReceivableDialogClick" :disabled="deleteClickType">
            导入明细
          </el-button>
        </div>
        <el-table
          :data="orderReceivableDetailTable"
          border
          style="width: 100%">
          <el-table-column prop="receivableNumber" label="对账单号" width="160">
          </el-table-column>
          <el-table-column prop="happenDate" label="发生时间" width="160">
          </el-table-column>
          <el-table-column prop="orderNumber" label="订单编号" width="160">
          </el-table-column>
          <el-table-column prop="receivableMoney" label="应收金额" width="100">
          </el-table-column>
          <el-table-column prop="adjustAmount" label="调整金额" width="100">
          </el-table-column>
          <el-table-column prop="invoiceAdjustLaterTotalAmount" label="调整后金额" width="100">
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="180">
            <template slot-scope="scope">
              <el-button type="danger" :disabled="deleteClickType"
                         @click.native.prevent="deleteRow(scope.$index, orderReceivableDetailTable)">删除
              </el-button>
              <el-button type="primary" :disabled="importDetail"
                         @click.native.prevent="adjustmentClick(scope.$index)">调整账单
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="f-mt10" v-bind:class="{ active: isActive }" :disabled="importDetail">
          <el-col :span="4">
            <div class="grid-content">调整金额</div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content ">
              <el-input v-model="invoiceForm.adjustAmount" type="number" @change="tzjeChange" class="f-ww60"
                        placeholder="调整金额"></el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content">实际应收总额</div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content ">
              <el-input v-model="invoiceTotalAmountAfter" :disabled="true" class="f-ww60"
                        placeholder="账单总额"></el-input>
            </div>
          </el-col>
        </el-row>

        <div slot="footer" class="dialog-footer">
          <el-button @click="invoicesDialogForm = false">取 消</el-button>
          <el-button type="primary" :disabled="qrclickType" @click="saveInvoice">确 定
          </el-button>
        </div>
      </el-dialog>

      <!--订单查看Dialog-->
      <el-dialog title="导入明细" :visible.sync="orderReceivableDetailDialog" size="large">
        <order-receivable :title="filters" @orderReceivables="getOrderReceivables"
                          @closeMsg="getCloseMsg"></order-receivable>
      </el-dialog>
    </div>
  </section>
</template>
<script>
import {
  search,
  save,
  modify,
  del,
  retrieve,
  invoiceStatus,
  invoiceIsAdjust,
  searchNoPage
} from '../../api/clearing/invoice.js';
import { getMemberUsers } from '../../api/customer/maintain.js';
import { isEmpty, resetObjNull, toFilters, getSelectObect } from '../../lib/util.js';
import OrderReceivable from '../clearing/OrderReceivableDialog.vue';

export default {
  components: {
    'order-receivable': OrderReceivable
  },
  data () {
    return {
      invoices: [],
      invoicesDialogForm: false,
      orderReceivableDetailDialog: false,
      clickType: false,
      qrclickType: false,
      importDetail: false,
      isActive: false,
      invoiceTotalAmountType: 1001,
      deleteClickType: false,
      memberUserTest: '',
      token: this.$store.state.token,
      dialogTitle: '',
      bo: false,
      memberUsers: [],
      filters: [],
      orderReceivableDetailForm: {
        costType: '',
        costTypeDictId: '',
        costTypeModel: '',
        costName: '',
        costNameDictId: '',
        costNameModel: '',
        receivableMoney: '',
        remark: ''
      },
      searchForm: {
        memberUserId_EQ: '',
        paymentType_EQ: '',
        createDate: '',
        invoiceNumber_LIKE: '',
        invoiceStatus_EQ: '',
        invoicePeriod: ''
      },
      index: 0,
      receivableMoney: '',
      test_t: null,
      test: null,
      orderReceivableDetailTable: [], // 费用明细table
      sels: [],
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: null,
      sortOrder: 'ascending',
      invoiceForm: {
        id: '',
        invoiceNumber: '',
        memberUserId: '',
        memberUserName: '',
        invoicePeriod: [],
        invoicePeriodStart: '',
        invoicePeriodEnd: '',
        invoiceTotalAmount: '',
        paymentType: '',
        paymentTypeName: '',
        paymentDate: '',
        invoiceDetailIds: [],
        invoiceDetails: [],
        invoiceAdjustLaterTotalAmount: '',
        adjustAmount: '',
        isAdjust: '',
        isAdjustName: ''
      },
      invoiceTotalAmountAfter: '',
      invoiceDetailIds: [],
      dataBk: ''// 时间
    };
  },
  methods: {
    // 多选操作
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchFormBtn();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchFormBtn();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchFormBtn();
    },
    // 对帐单导出
    invoiceExpress () {
      searchNoPage({
        filters: '',
        sorts: '-createDate'
      }).then((res) => {
        if (res.data.successFlg) {
          this.$ue.downloadFile(res.data.detailModelList.map(item => [item.createDate, item.invoiceNumber, item.invoicePeriodStart, item.invoicePeriodEnd, item.invoiceStatusName, item.invoiceTotalAmount, item.isAdjustName, item.paymentDate, item.paymentTypeName, item.residueAmount]), ['创单时间 ', '帐单编号', '账单周期(起)', '账单周期(讫)', '账单状态', '帐单总金额', '是否调整', '结算日期', '支付方式', '剩余金额'], '对帐单导出文件');
        } else {
          return this.$message.error('目前暂无数据，无法导出');
        }
      });
    },
    adjustmentClick (index) {
      this.$prompt('请输入调整金额', '提示', {
        inputPattern: /^-?\d+\.?\d{0,2}$/,
        inputErrorMessage: '格式不正确'
      }).then((value) => {
        this.orderReceivableDetailTable[index].adjustAmount = parseFloat(value.value);
        let vu = this.orderReceivableDetailTable[index].receivableMoney;
        this.orderReceivableDetailTable[index].receivableMoney = parseFloat(vu) + parseFloat(1);
        this.orderReceivableDetailTable[index].receivableMoney = vu;
        this.orderReceivableDetailTable[index].adjustAmount = parseFloat(value.value);
        this.orderReceivableDetailTable[index].invoiceAdjustLaterTotalAmount = parseFloat(this.orderReceivableDetailTable[index].receivableMoney) + parseFloat(this.orderReceivableDetailTable[index].adjustAmount);
        let money = 0;
        for (let ordt in this.orderReceivableDetailTable) {
          if (!isEmpty(this.orderReceivableDetailTable[ordt].invoiceAdjustLaterTotalAmount)) {
            money = money + this.orderReceivableDetailTable[ordt].invoiceAdjustLaterTotalAmount;
          }
        }
        if (!isEmpty(this.invoiceForm.adjustAmount)) {
          money = parseFloat(this.invoiceForm.adjustAmount) + money;
        }
        this.invoiceTotalAmountAfter = Math.round(money * 100) / 100;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消调整'
        });
      });
    },
    tzjeChange (val) {
      if (isEmpty(val)) {
        val = 0;
      }
      let sourceNum = 0;
      for (let ordts in this.orderReceivableDetailTable) {
        if (!isEmpty(this.orderReceivableDetailTable[ordts].invoiceAdjustLaterTotalAmount)) {
          sourceNum = parseFloat(sourceNum) + parseFloat(this.orderReceivableDetailTable[ordts].invoiceAdjustLaterTotalAmount);
        }
      }
      let sum = parseFloat(sourceNum) + parseFloat(val);
      this.invoiceTotalAmountAfter = sum.toFixed(2);
    },
    deleteInvoice (val) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        del(val).then((res) => {
          if (res.data.successFlg) {
            this.message('删除成功!');
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /**
       *获取账单明细
       */
    getCloseMsg (val) {
      this.orderReceivableDetailDialog = false;
    },
    getOrderReceivables (val) {
      this.orderReceivableDetailDialog = false;
      let sources = this.invoiceForm.invoiceDetails;
      let ors = sources.concat(val);
      this.orderReceivableDetailTable = [];
      this.orderReceivableDetailTable = ors;

      let money = 0;
      for (let ordt in this.orderReceivableDetailTable) {
        if (!isEmpty(this.orderReceivableDetailTable[ordt].invoiceAdjustLaterTotalAmount)) {
          money = money + this.orderReceivableDetailTable[ordt].invoiceAdjustLaterTotalAmount;
        }
      }
      this.invoiceForm.invoiceTotalAmount = Math.round(money * 100) / 100;
      if (isEmpty(this.invoiceForm.adjustAmount)) {
        this.invoiceForm.adjustAmount = 0;
      }
      let sum = parseFloat(this.invoiceForm.invoiceTotalAmount) + parseFloat(this.invoiceForm.adjustAmount);
      this.invoiceTotalAmountAfter = sum.toFixed(2);
    },
    importOrderReceivableDialogClick () {
      if (isEmpty(this.invoiceForm.memberUserId)) {
        return this.$message.error('请先选择客户');
      }
      if (isEmpty(this.invoiceForm.paymentType)) {
        return this.$message.error('请先选择结算方式');
      }
      if (this.invoiceForm.invoicePeriod.length < 2) {
        return this.$message.error('请先选择账单周期');
      }
      let receivableNumbers = this.orderReceivableDetailTable.map(ord => {
        return ord.receivableNumber;
      }).join(',');
      let orFilters = {memberUserId: this.invoiceForm.memberUserId, receivableType: this.invoiceForm.paymentType};
      let signOffFilters = {s: this.invoiceForm.invoicePeriod[0], e: this.invoiceForm.invoicePeriod[1]};
      this.filters = [orFilters, signOffFilters, {receivableNumbers: receivableNumbers}, Date.now()];
      this.orderReceivableDetailDialog = true;
    },
    confirmClick (id, status) {
      this.$confirm('是否要更改该条数据？', '提示', {
        type: 'warning'
      }).then(() => {
        invoiceStatus(id, status).then((res) => {
          if (res.data.successFlg) {
            this.message('更改成功!');
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    invoiceIsAdjustClick (id, status) {
      this.$confirm('是否要更改该条数据？', '提示', {
        type: 'warning'
      }).then(() => {
        invoiceIsAdjust(id, status).then((res) => {
          if (res.data.successFlg) {
            this.message('更改成功!');
            this.searchInvoices('');
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    /**
       *  编辑对账单
       */
    compileClick (val) {
      this.dialogTitle = '编辑对账单';
      this.invoicesDialogForm = true;
      this.invoiceTotalAmountType = 1001;
      this.clickType = false;
      this.qrclickType = false;
      this.isActive = true;
      this.importDetail = true;
      this.retrieve(val);
    },
    selectClick (val) {
      this.dialogTitle = '查看对账单';
      this.invoiceTotalAmountType = 1001;
      this.invoicesDialogForm = true;
      this.deleteClickType = true;
      this.isActive = true;
      this.clickType = true;
      this.qrclickType = true;
      this.importDetail = true;
      this.retrieve(val);
    },
    /**
       *调整对账单
       */
    adjustClick (val) {
      this.dialogTitle = '对账调整';
      this.invoiceTotalAmountType = 1002;
      this.invoicesDialogForm = true;
      this.clickType = true;
      this.deleteClickType = false;
      this.qrclickType = false;
      this.isActive = false;
      this.importDetail = false;
      this.retrieve(val);
    },
    retrieve (id) {
      retrieve(id).then((res) => {
        if (res.data.successFlg) {
          this.invoiceForm = res.data.obj;
          this.invoiceTotalAmountAfter = this.invoiceForm.invoiceAdjustLaterTotalAmount;
          this.invoiceForm.invoicePeriod = [new Date(res.data.obj.invoicePeriodStart), new Date(res.data.obj.invoicePeriodEnd)];
          this.orderReceivableDetailTable = res.data.obj.invoiceDetails;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    invoicesDialogClick () {
      resetObjNull(this.invoiceForm);
      this.invoiceForm.invoicePeriod = [];
      this.orderReceivableDetailTable = [];
      this.invoiceTotalAmountAfter = '';
      this.clickType = false;
      this.qrclickType = false;
      this.isActive = true;
      this.invoiceTotalAmountType = 1001;
      this.importDetail = true;
      this.dialogTitle = '新增对账单';
      this.invoicesDialogForm = true;
      this.invoiceForm.invoiceNumber = 'ZD' + new Date().getTime();
    },
    searchMemberUsersChange (event) {
      this.invoiceForm.memberUserId = event.id;
      this.invoiceForm.memberUserName = event.realName;
    },

    searchCostTypeChange () {
      this.orderReceivableDetailForm.costType = this.orderReceivableDetailForm.costTypeModel.cnDictValname;
      this.orderReceivableDetailForm.costTypeDictId = this.orderReceivableDetailForm.costTypeModel.dictVal;
    },
    searchCostNameChange () {
      this.orderReceivableDetailForm.costName = this.orderReceivableDetailForm.costNameModel.cnDictValname;
      this.orderReceivableDetailForm.costNameDictId = this.orderReceivableDetailForm.costNameModel.dictVal;
    },
    searchMemberUsers (val) {
      let filters = 'realName?' + val + ';';
      if (!isEmpty(val)) {
        getMemberUsers({
          token: this.token,
          filters: filters + 'status=111002001',
          sorts: '',
          size: '15',
          page: '1'
        }).then((res) => {
          this.memberUsers = res.data.detailModelList;
        });
      }
    },
    deleteRow (index, rows) {
      this.invoiceDetailIds.push(rows[index].id);
      rows.splice(index, 1);
      let money = 0;
      for (let ordt in this.orderReceivableDetailTable) {
        if (!isEmpty(this.orderReceivableDetailTable[ordt].invoiceAdjustLaterTotalAmount)) {
          money = money + this.orderReceivableDetailTable[ordt].invoiceAdjustLaterTotalAmount;
        }
      }
      if (!isEmpty(this.invoiceForm.adjustAmount)) {
        money = money + parseFloat(this.invoiceForm.adjustAmount);
      }
      this.invoiceTotalAmountAfter = this.invoiceForm.invoiceTotalAmount = Math.round(money * 100) / 100;
    },
    /**
       * 新增&修改对账单
       */
    saveInvoice () {
      if (this.orderReceivableDetailTable.length <= 0) {
        return this.$message.error('请填写对账单详情');
      }
      this.$refs['invoiceForm'].validate((invoiceFormValid) => {
        if (invoiceFormValid) {
          this.invoiceForm.paymentTypeName = getSelectObect(this.invoiceForm.paymentType, 'dictVal', this.$store.getters.PAY_WAY).cnDictValname;
          this.invoiceForm.memberUserName = getSelectObect(this.invoiceForm.memberUserId, 'userId', this.memberUsers).realName;
          this.invoiceForm.invoicePeriodStart = this.invoiceForm.invoicePeriod[0];
          this.invoiceForm.invoicePeriodEnd = this.invoiceForm.invoicePeriod[1];
          this.invoiceForm.invoiceDetails = this.orderReceivableDetailTable;
          this.$refs['invoiceForm'].validate((invoice) => {
            if (invoice) {
              if (isEmpty(this.invoiceForm.id)) {
                save(this.invoiceForm).then((res) => {
                  if (res.data.successFlg) {
                    this.message('对账单生成成功');
                  } else {
                    this.$message.error('对账单生成失败');
                  }
                });
              } else {
                this.invoiceForm.invoiceDetailIds = [];
                this.invoiceForm.invoiceDetailIds = this.invoiceDetailIds;
                this.invoiceForm.invoiceAdjustLaterTotalAmount = this.invoiceTotalAmountAfter;
                modify(this.invoiceForm).then((res) => {
                  if (res.data.successFlg) {
                    this.message('对账单修改成功');
                  } else {
                    this.$message.error('对账单修改失败');
                  }
                });
              }
            }
          });
        }
      });
    },
    message (msg) {
      this.invoicesDialogForm = false;
      this.$message.success(msg);
      this.searchInvoices('');
    },
    searchInvoices (filters) {
      search({
        filters: filters,
        sorts: '-createDate',
        size: this.pageSize,
        page: this.currentPage
      }).then((res) => {
        if (res.data.successFlg) {
          this.invoices = res.data.detailModelList;
          this.currentPage = res.data.currPage;
          this.total = res.data.totalCount;
          this.pageSize = res.data.pageSize;
        }
      });
    },
    getMemberUsers () {
      getMemberUsers({
        page: 1,
        size: 15,
        filters: 'status=111002001',
        sorts: ''
      }).then((res) => {
        this.memberUsers = res.data.detailModelList;
      });
    },
    resetSearchForm () {
      resetObjNull(this.searchForm);
    },
    searchFormBtn () {
      let filters = toFilters(this.searchForm);
      if (!isEmpty(this.searchForm.invoicePeriod)) {
        let start = this.searchForm.invoicePeriod[0].Format('yyyy-MM-dd');
        let end = this.searchForm.invoicePeriod[1].Format('yyyy-MM-dd');
        filters += ';invoicePeriodStart>=' + start + ';invoicePeriodEnd<=' + end;
      }
      this.searchInvoices(filters);
    },

    /**
       * 计算应收总金额
       */
    calculatePrice () {
      let money = 0;
      for (let ordt in this.orderReceivableDetailTable) {
        money = money + this.orderReceivableDetailTable[ordt].invoiceAdjustLaterTotalAmount;
      }
      this.invoiceForm.invoiceTotalAmount = Math.round(money * 100) / 100;
    }
  },
  mounted () {
    this.searchInvoices('');
    this.getMemberUsers();
    this.$store.commit('initDict');
  }
};
</script>
